<template>
  <div>
    <el-dialog
      title="新增指令配置"
      :visible.sync="dialogVisible"
      width="500px"
      :before-close="closeEditDialog"
      :close-on-click-modal="false"
      :append-to-body="true"
    >
      <el-form
        :model="addForm"
        :rules="rules"
        ref="refAddInfo"
        label-width="110px"
      >
        <el-form-item size="small" label="指令名称" prop="name">
          <el-input
            clearable
            v-model.trim="addForm.name"
            placeholder="请输入"
            maxlength="30"
          ></el-input>
        </el-form-item>
        <div class="deviceModel">
          <el-form-item size="small" label="指令标识符" class="is-required">
          </el-form-item>
          <div style="flex: 1">
            <!-- 服务选择 -->
            <el-form-item
              size="small"
              label-width="0"
              :prop="`actions[${0}].config.services[0].identifier`"
              :rules="[
                {
                  required: true,
                  message: '请选择',
                  trigger: 'change',
                },
              ]"
            >
              <el-select
                v-model="addForm.actions[0].config.services[0].identifier"
                @change="serviceSelected"
                filterable
                placeholder="请选择"
                style="width: 100%"
              >
                <el-option
                  v-for="s in servicesList || []"
                  :label="s.name"
                  :value="s.identifier"
                  :key="s.identifier"
                />
              </el-select>
            </el-form-item>
            <!-- 输入选择 -->
            <el-form-item
              size="small"
              label-width="0"
              :prop="`actions[${0}].config.services[0].equalValue`"
              :rules="[
                {
                  required: true,
                  message: '请选择',
                  trigger: 'change',
                },
              ]"
              v-if="addForm.actions[0].config.services[0].identifier"
            >
              <el-select
                v-model="addForm.actions[0].config.services[0].equalValue"
                @change="
                  serviceSelectedItem(
                    $event,
                    addForm.actions[0].config.services[0].inputData
                  )
                "
                filterable
                size="small"
                placeholder="请选择"
                style="width: 100%"
              >
                <el-option
                  v-for="s in addForm.actions[0].config.services[0].inputData ||
                  []"
                  :label="s.name"
                  :value="s.identifier"
                  :key="s.identifier"
                />
              </el-select>
            </el-form-item>
            <!-- 具体动作 -->
            <div
              style="display: flex"
              v-if="addForm.actions[0].config.services[0].equalValue"
            >
              <el-form-item
                size="small"
                label-width="0"
                style="width: 100%"
                v-if="
                  currentDataItem.dataType.type == 'enum' ||
                  currentDataItem.dataType.type == 'bool'
                "
                :prop="`actions[${0}].config.services[0].inputData[0].value`"
                :rules="[
                  {
                    required: true,
                    message: '请选择',
                    trigger: 'change',
                  },
                ]"
              >
                <el-select
                  v-model="
                    addForm.actions[0].config.services[0].inputData[0].value
                  "
                  @change="forceUpdate(true)"
                  filterable
                  size="small"
                  placeholder="请选择"
                  style="width: 100%"
                >
                  <el-option
                    v-for="s in currentDataItem.dataType.typeList || []"
                    :label="s.label"
                    :value="s.value"
                    :key="s.value"
                  />
                </el-select>
              </el-form-item>

              <!-- 服务 int32 -->
              <el-form-item
                size="small"
                label-width="0"
                style="width: 100%"
                :prop="`actions[${0}].config.services[0].inputData[0].value`"
                :rules="[
                  {
                    required: true,
                    message: '请输入',
                    trigger: 'blur',
                  },
                ]"
                v-if="currentDataItem.dataType.type == 'int32'"
              >
                <el-input
                  v-model="
                    addForm.actions[0].config.services[0].inputData[0].value
                  "
                  auto-complete="off"
                  @input="forceUpdate"
                  style="width: 100%"
                  size="small"
                  :placeholder="
                    currentDataItem.dataType.specs.min +
                    '-' +
                    currentDataItem.dataType.specs.max
                  "
                  :oninput="`if(isNaN(value)) { value = null } {if(value>${currentDataItem.dataType.specs.max})value=${currentDataItem.dataType.specs.max}} {if(value<${currentDataItem.dataType.specs.min})value=${currentDataItem.dataType.specs.min}}`"
                />
              </el-form-item>
              <!-- 服务 float -->
              <el-form-item
                size="small"
                label-width="0"
                style="width: 100%"
                :prop="`actions[${0}].config.services[0].inputData[0].value`"
                :rules="[
                  {
                    required: true,
                    message: '请输入',
                    trigger: 'blur',
                  },
                ]"
                v-else-if="currentDataItem.dataType.type == 'float'"
              >
                <el-input
                  v-model="
                    addForm.actions[0].config.services[0].inputData[0].value
                  "
                  auto-complete="off"
                  size="small"
                  style="width: 100%"
                  @input="forceUpdate"
                  :placeholder="
                    currentDataItem.dataType.specs.min +
                    '-' +
                    currentDataItem.dataType.specs.max
                  "
                  :oninput="`if(value.indexOf('.')>0){value=value.slice(0,value.indexOf('.')+3)} {if(value>${currentDataItem.dataType.specs.max})value=${currentDataItem.dataType.specs.max}} {if(value<${currentDataItem.dataType.specs.min})value=${currentDataItem.dataType.specs.min}}`"
                />
              </el-form-item>
              <!-- 服务 text -->
              <el-form-item
                size="small"
                label-width="0"
                style="width: 100%"
                :prop="`actions[${0}].config.services[0].inputData[0].value`"
                :rules="[
                  {
                    required: true,
                    message: '请输入',
                    trigger: 'blur',
                  },
                ]"
                v-else-if="currentDataItem.dataType.type == 'text'"
              >
                <el-input
                  v-model="
                    addForm.actions[0].config.services[0].inputData[0].value
                  "
                  auto-complete="off"
                  size="small"
                  style="width: 100%"
                  @input="forceUpdate"
                  placeholder="请输入"
                  :maxlength="currentDataItem.dataType.specs.length"
                />
              </el-form-item>
              <!-- 服务 date -->
              <el-form-item
                size="small"
                label-width="0"
                style="width: 100%"
                :prop="`actions[${0}].config.services[0].inputData[0].value`"
                :rules="[
                  {
                    required: true,
                    message: '请输入',
                    trigger: 'blur',
                  },
                ]"
                v-else-if="currentDataItem.dataType.type == 'date'"
              >
                <el-input
                  v-model="
                    addForm.actions[0].config.services[0].inputData[0].value
                  "
                  auto-complete="off"
                  style="width: 100%"
                  size="small"
                  placeholder="毫秒"
                  @input="forceUpdate"
                />
              </el-form-item>
            </div>
          </div>
        </div>

        <el-form-item size="small" label="指令内容" prop="commandInfo">
          <el-input
            type="textarea"
            :rows="2"
            placeholder="请输入"
            maxlength="100"
            v-model.trim="addForm.commandInfo"
            resize="none"
            :autosize="{ minRows: 2, maxRows: 5 }"
          >
          </el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button size="small" @click="closeEditDialog" class="cancel-button"
          >取 消</el-button
        >
        <el-button
          size="small"
          @click="editSubmit"
          v-preventReClick="1000"
          class="confirm-button"
          >确 定</el-button
        >
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { reqThingCommandSave } from "@/api/model";
import { mapState } from "vuex";

export default {
  name: "add",
  props: ["deviceType", "model", "thingModelId"],
  components: {},
  data() {
    return {
      dialogVisible: false,
      manufacturerList: [],
      addForm: {
        name: "",
        commandInfo: "",
        actions: [
          {
            config: {
              id: Date.now(),
              services: [
                {
                  // 设备控制
                  identifier: "",
                  inputData: [
                    {
                      identifier: "",
                      dataType: {
                        type: "",
                        specs: {},
                      },
                      name: "",
                      required: false,
                      value: "",
                    },
                  ],
                  saved: true,
                  value: "",
                  equalValue: "",
                },
              ],
              pk: "", // 设备主键：门磁
              radius: {
                type: "all", //类型： all 全部 、org 组织、 space 单位、 device 设备
                assemble: [], //集合id
                deviceDn: [],
                spaceDn: [],
                orgDn: [],
              },
              identifier: "",
              pkIds: "",
              checked: true,
              classMark: "",
            },
            type: "", // 类型：设备控制: device  通知: alert
          },
        ],
      },
      rules: {
        name: [{ required: true, message: "请输入指令名称", trigger: "blur" }],
        commandInfo: [
          { required: true, message: "请输入指令内容", trigger: "blur" },
        ],
      },
      currentDataItem: {},
      servicesList: [],
    };
  },
  watch: {
    model: {
      handler(val) {
        this.initThingModel();
      },
      deep: true,
    },
  },
  computed: {
    ...mapState(["user"]),
  },
  methods: {
    // 物模型数据处理
    initThingModel() {
      this.servicesList = [];
      if (!this.model.services.length) return;
      this.model.services.forEach((s) => {
        this.servicesList.push(s);
      });
    },
    // 服务
    serviceSelected(e) {
      this.servicesList.forEach((s) => {
        if (e == s.identifier) {
          if (s.inputData.length) {
            s.inputData.forEach((item) => {
              if (item.dataType.type == "enum") {
                item.dataType.typeList = Object.entries(
                  item.dataType.specs
                ).map(([key, value]) => {
                  if (/^\d+$/.test(key)) {
                    // 如果是数字字符串，使用 parseInt 转换为数字
                    return { label: value, value: parseInt(key, 10) };
                  } else {
                    // 如果是普通字符串，直接使用字符串
                    return { label: value, value: key };
                  }
                });
              } else if (item.dataType.type == "bool") {
                item.dataType.typeList = Object.entries(
                  item.dataType.specs
                ).map(([key, value]) => {
                  // return { label: value, value: parseInt(key, 10) };
                  if (/^\d+$/.test(key)) {
                    // 如果是数字字符串，使用 parseInt 转换为数字
                    return { label: value, value: parseInt(key, 10) };
                  } else {
                    // 如果是普通字符串，直接使用字符串
                    return { label: value, value: key };
                  }
                });
              }
              this.addForm.actions[0].config.services[0].inputData =
                s.inputData;
              this.currentDataItem = {};
            });
          }
        }
      });
    },
    serviceSelectedItem(e, arr) {
      arr.forEach((s) => {
        if (e == s.identifier) {
          this.currentDataItem = s;
          if (s.dataType.type == "json") {
            this.addForm.actions[0].config.services[0].value = s.dataType.specs;
          }
        }
      });
      this.forceUpdate(true);
    },
    // 强制更新
    forceUpdate(isPass = false) {
      this.$forceUpdate();
    },
    // 点击
    async editSubmit() {
      this.$refs.refAddInfo.validate(async (valid) => {
        if (valid) {
          let services = this.addForm.actions[0].config.services;
          console.log(services, "services");
          this.addForm.identifier = `${services[0].identifier}_${services[0].inputData[0].identifier}_${services[0].inputData[0].value}`;
          console.log(this.addForm.identifier, "this.addForm.identifier");
          let addForm_copy = JSON.parse(JSON.stringify(this.addForm));
          const res = await reqThingCommandSave({
            thingModelId: this.thingModelId,
            ...addForm_copy,
          });
          // console.log(res);
          if (res.code !== 20000) return this.$modal.notifyWarning(res.message);
          this.$modal.notifySuccess("添加产品型号成功");
          this.$parent.ProductModelPage();
          this.closeEditDialog();
        }
      });
    },
    // 点击关闭弹框
    closeEditDialog() {
      this.$refs.refAddInfo.resetFields();
      this.dialogVisible = false;
    },
  },
  mounted() {},
  created() {},
};
</script>

<style lang="less" scoped>
@import url("../../../common.less");

.deviceModel {
  width: 100%;
  display: flex;
  flex-wrap: wrap;
}
</style>
